package com.jy.api.service.impl;

import com.jy.api.dao.TableSalesCodeDao;
import com.jy.api.domain.TableSalesCode;
import com.jy.api.service.TableSalesCodeService;
import com.jy.api.signUpReq.SalesCode.UpdateSalesCodeReq;
import com.jy.api.util.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Random;


/**
 * Created by xiaohua
 * on 2019/3/29.
 */
@Service
public class TableSalesCodeServiceImpl implements TableSalesCodeService {
    @Autowired
    private TableSalesCodeDao codeDao;


    @Override
    public Result findByCodeName(String codeName) {
        TableSalesCode enabled = codeDao.findByCodeAndEnabled(codeName, true);
        if (enabled==null){
            return new Result(400,"该推荐码不存在，请联系相关人员！");
        }
        if (enabled.getCount()>0){
                    return new Result(200,"校验成功，请继续操作");
        }else {
            return new Result(400,"推荐码次数不足，请联系相关人员！");
        }

    }

    @Override
    public Page<TableSalesCode> findAllCode(String mobile, Pageable pageable) {
        Page<TableSalesCode> page ;
        if (StringUtils.equals("13980547109",mobile)){
            page = codeDao.findAllByParentUserNameIsNullOrderByCountDesc(pageable);
            return page;
        }else {
            page=null;
            return page;
        }
    }

    @Override
    public Result updateCode(UpdateSalesCodeReq req) {
        TableSalesCode code = codeDao.findOne(req.getId());
        code.setCount(req.getCount());
        code.setEnabled(req.isEnabled());
        codeDao.save(code);
        return new Result(200,"修改成功");
    }

    @Override
    public Result addCode(UpdateSalesCodeReq req) {
        TableSalesCode code = codeDao.findByUserName(req.getMobile());
        if (code==null){
        String co=  getReferralCode();
           TableSalesCode c = new TableSalesCode(co,req);
           codeDao.save(c);
           return new Result(200,"添加成功");
        }else {
            return new Result(200,"该手机号已存在，请重新填写");
        }
    }

    //生产随机邀请码
    private String getReferralCode() {
        String code = "hxbs";
        Random random = new Random();
        Integer number = random.nextInt(999999);
        code += number;
        TableSalesCode c = codeDao.findByCode(code);
        if (c != null) {
            code = getReferralCode();
        }
        return code;
    }








}
